<?php

class ActionProcessing extends CoreController {

	function __construct()
	{
		parent::__construct();
	}

	public static function init($className=__CLASS__)
	{
		return new $className;
	}

	public function ActionRunning()
	{
		add_action('init',array($this,'fixWPRedirect'));
        add_action('init',array($this,'registerSessions'));
		add_action('add_meta_boxes',array($this,'addPostMetaSingle'));
		add_action('admin_enqueue_scripts',array($this,'admin_script'));
		add_action('admin_menu', array($this,'registerAdminMenu'));
		add_action('admin_init', array($this,'registerAdminSettings'));
		add_action('wp_ajax_saveUserProfile',array($this,'saveUserProfile'));
		add_action('wp_ajax_nopriv_saveUserProfile',array($this,'saveUserProfile'));
		add_action('wp_ajax_savePracticeTestInformation',array($this,'savePracticeTestInformation'));
		add_action('wp_ajax_nopriv_savePracticeTestInformation',array($this,'savePracticeTestInformation'));
		add_action('wp_ajax_savePracticeTestQuestion',array($this,'savePracticeTestQuestion'));
		add_action('wp_ajax_nopriv_savePracticeTestQuestion',array($this,'savePracticeTestQuestion'));
		add_action('wp_ajax_applyPracticeTestAnswer',array($this,'applyPracticeTestAnswer'));
		add_action('wp_ajax_nopriv_applyPracticeTestAnswer',array($this,'applyPracticeTestAnswer'));
		add_action('wp_ajax_removePracticeTestQuestion',array($this,'removePracticeTestQuestion'));
		add_action('wp_ajax_nopriv_removePracticeTestQuestion',array($this,'removePracticeTestQuestion'));
		add_action('wp_ajax_createEmailAJAX',array($this,'createEmailAJAX'));
		add_action('wp_ajax_nopriv_createEmailAJAX',array($this,'createEmailAJAX'));
		add_action('wp_ajax_checkFaceBookUser',array($this,'checkFaceBookUser'));
		add_action('wp_ajax_nopriv_checkFaceBookUser',array($this,'checkFaceBookUser'));
		add_action('wp_ajax_updateStatusFaceBookUser',array($this,'updateStatusFaceBookUser'));
		add_action('wp_ajax_nopriv_updateStatusFaceBookUser',array($this,'updateStatusFaceBookUser'));
		add_action('wp_ajax_updatePracticeTestTemporaryResult',array($this,'updatePracticeTestTemporaryResult'));
		add_action('wp_ajax_nopriv_updatePracticeTestTemporaryResult',array($this,'updatePracticeTestTemporaryResult'));
		add_action('wp_ajax_autoUpdatePracticeTest',array($this,'autoUpdatePracticeTest'));
		add_action('wp_ajax_nopriv_autoUpdatePracticeTest',array($this,'autoUpdatePracticeTest'));
		add_action('wp_ajax_startPracticeTest',array($this,'startPracticeTest'));
		add_action('wp_ajax_nopriv_startPracticeTest',array($this,'startPracticeTest'));
		add_action('wp_ajax_saveHostingReviews',array($this,'saveHostingReviews'));
		add_action('wp_ajax_nopriv_saveHostingReviews',array($this,'saveHostingReviews'));
		add_action('save_post',array($this,'savePostMetaSingle'));
		add_action('save_post',array($this,'savePostMetaHostingReviews'));
		add_action('init',array($this,'series_tax'));
	}

	public function series_tax() {
		$labels = array(
			'name' => _x('Series', 'taxonomy general name'),
			'singular_name' => _x('Series', 'taxonomy singular name'),
			'all_items' => __('All Series'),
			'edit_item' => __('Edit Series'), 
			'update_item' => __('Update Series'),
			'add_new_item' => __('Add New Series'),
			'new_item_name' => __('New Series Name'),
			'menu_name' => __('Series'),
		);

		register_taxonomy(
			'series',
			array('post'),
			array(
				'hierarchical' => true,
				'labels' => $labels,
				'show_ui' => true,
				'query_var' => true,
				'rewrite' => array('slug' => 'series'),
			)
		);
	} 

	public function addPostMetaSingle()
	{
		$this->loadModel('CategoryModel');
		global $post;
		add_meta_box('PostMetaSingle','Post Meta Single',array($this,'createPostMetaSingle'),'post');
		add_meta_box('PracticeTest','Practice Test',array($this,'createPracticeTest'),'post');
		if($this->CategoryModel->isCategoryReview($post->ID)){
			add_meta_box('PostMetaHostingReviews','Hosting Reviews',array($this,'createHostingReviews'),'post');
		}
	}

	public function createPostMetaSingle()
	{
		global $post;
		wp_nonce_field('singleMeta','singleMeta-nonce-field');
		$this->updateDataMeta($post->ID);
		$this->render('postmeta',array(
			'meta_level'=>get_post_meta($post->ID,'meta-level',true),
			'meta_time'=>get_post_meta($post->ID,'meta-time',true),
			'meta_require'=>get_post_meta($post->ID,'meta-require',true),
			'meta_filesize'=>get_post_meta($post->ID,'meta-filesize',true),
			'meta_youtube'=>get_post_meta($post->ID,'meta-youtube',true),
			'meta_linkdemo'=>get_post_meta($post->ID,'meta-linkdemo',true),
			'meta_linksource'=>get_post_meta($post->ID,'meta-linksource',true),
			'meta_linktorrent'=>get_post_meta($post->ID,'meta-linktorrent',true),
			'meta_linkmediafire'=>get_post_meta($post->ID,'meta-linkmediafire',true),
			'meta_question'=>get_post_meta($post->ID,'meta-question',true)
		));
	}

	public function updateDataMeta($post_id)
	{
		$meta_youtube = get_post_meta($post_id,'meta-youtube',true);
		$meta_level = get_post_meta($post_id,'meta-level',true);
		$meta_require = get_post_meta($post_id,'meta-require',true);
		$meta_time = get_post_meta($post_id,'meta-time',true);
		$meta_filesize = get_post_meta($post_id,'meta-filesize',true);
		$meta_linkdemo = get_post_meta($post_id,'meta-linkdemo',true);
		$meta_linksource = get_post_meta($post_id,'meta-linksource',true);
		$meta_linktorrent = get_post_meta($post_id,'meta-linktorrent',true);
		$meta_linkmediafire = get_post_meta($post_id,'meta-linkmediafire',true);
		$meta_question = get_post_meta($post_id,'meta-question',true);
		$list = array('post_detail_level'=>'meta-level','post_detail_need'=>'meta-require','post_detail_time'=>'meta-time','post_detail_size'=>'meta-filesize','post_detail_demo'=>'meta-linkdemo','post_detail_source'=>'meta-linksource','post_detail_torrent'=>'meta-linktorrent','post_detail_mediafire'=>'meta-linkmediafire');
		$cData = get_post_meta($post_id,'_my_meta',true);
		foreach($list as $key=>$value){
			$val = get_post_meta($post_id,$value,true);
			if(!empty($cData[$key]) && empty($val)){
				update_post_meta($post_id,$value,$cData[$key]);
			}
		}
	}

	public function savePostMetaSingle($post_id)
	{
		if($this->checkNonceField($post_id,'singleMeta-nonce-field')){
			$meta_key = array('meta-level','meta-require','meta-time','meta-filesize','meta-youtube','meta-linkdemo','meta-linksource','meta-linktorrent','meta-linkmediafire','meta-question');
			$meta_key_video = array('meta-question','meta-youtube','meta-linktorrent','meta-linkmediafire');
			$meta_youtube = get_post_meta($post_id,'meta-youtube',true);
			$meta_checkvideo = get_post_meta($post_id,'meta-question',true);
			foreach($_POST as $key=>$value){
				if(isset($_POST[$key]) && in_array($key,$meta_key)){
					$metadata = stripslashes(strip_tags($_POST[$key]));
					if(empty($metadata)){
						delete_post_meta($post_id,$key);
					}else{
						if($meta_checkvideo=="YES" || ($metadata=="YES" && in_array($key,$meta_key_video))){
							if($key=="meta-question"){
								update_post_meta($post_id,$key,$metadata);
							}
							if($key=="meta-youtube"){
								update_post_meta($post_id,$key,$metadata);
							}
							if($key=="meta-linktorrent"){
								update_post_meta($post_id,$key,$metadata);
							}
							if($key=="meta-linkmediafire"){
								update_post_meta($post_id,$key,$metadata);
							}
						}else{
							update_post_meta($post_id,$key,$metadata);
						}
					}
				}
			}
		}
	}

	public function checkNonceField($post_id,$nonce)
	{
		$is_autosave = wp_is_post_autosave($post_id);
		$is_revision = wp_is_post_revision($post_id);
		$is_valid_nonce = (isset($_POST[$nonce]) && wp_verify_nonce($_POST[$nonce],'singleMeta'));
		return !($is_autosave || $is_revision) && $is_valid_nonce;
	}

	public function createHostingReviews()
	{
		global $post;
		wp_nonce_field('HostingReviews','HostingReviews-nonce-field');
		$this->render('postmeta-hosting',array(
			'review_hosting'=>get_post_meta($post->ID,'review-hosting',true),
			'review_support'=>get_post_meta($post->ID,'review-support',true),
			'review_properties'=>get_post_meta($post->ID,'review-properties',true),
			'review_download'=>get_post_meta($post->ID,'review-download',true),
			'review_upload'=>get_post_meta($post->ID,'review-upload',true),
			'review_desert'=>get_post_meta($post->ID,'review-desert',true)
		));
	}

	public function savePostMetaHostingReviews($post_id)
	{
		$this->loadModel('CategoryModel');
		if($this->checkNonceFieldHostingReviews($post_id,'HostingReviews-nonce-field')){
			$metaHosting = array('review-hosting','review-support','review-properties','review-download','review-upload','review-desert');
			if($this->CategoryModel->isCategoryReview($post_id)){
				foreach($_POST as $key=>$value){
					if(isset($_POST[$key]) && in_array($key,$metaHosting)){
						$metadata = stripslashes(strip_tags($_POST[$key]));
						if(empty($metadata)){
							delete_post_meta($post_id,$key);
						}else{
							update_post_meta($post_id,$key,$metadata);
						}
					}
				}
			}
		}
	}

	public function saveHostingReviews()
	{
		$this->loadModel('CategoryModel');
		if($this->CategoryModel->isCategoryReview($_POST['review_postID'])){
			$metaHosting = array('review_hosting','review_support','review_properties','review_download','review_upload','review_desert','review_userID');
			$postID = $_POST['review_postID'];
			$isUserReview = get_post_meta($postID,$_POST['review_userID'],true);
			if($isUserReview !== "YES"){
				foreach($_POST as $key=>$value){
					if(isset($_POST[$key]) && in_array($key,$metaHosting)){
						$metadata = stripslashes(strip_tags($_POST[$key]));
						$keyMeta = str_replace("_","-",$key);
						$reviewAttr = get_post_meta($postID,$keyMeta,true);
						if($key=="review_userID"){
							update_post_meta($postID,$_POST['review_userID'],"YES");
						}else{
							if(strlen($reviewAttr)==0 || $reviewAttr==0){
								update_post_meta($postID,$keyMeta,$metadata);
							}else{
								update_post_meta($postID,$keyMeta,round((($metadata+$reviewAttr)/2),2));
							}
						}
					}else{
						continue;
					}
				}
				wp_send_json_success();
			}else{
				wp_send_json_error();
			}
		}else{
			wp_send_json_error();
		}
	}

	public function checkNonceFieldHostingReviews($post_id,$nonce)
	{
		$is_autosave = wp_is_post_autosave($post_id);
		$is_revision = wp_is_post_revision($post_id);
		$is_valid_nonce = (isset($_POST[$nonce]) && wp_verify_nonce($_POST[$nonce],'HostingReviews'));
		return !($is_autosave || $is_revision) && $is_valid_nonce;
	}

	public function createEmailAJAX()
	{
		if(!empty($_POST['email']) && !empty($_POST['subject']) && !empty($_POST['messages'])){
			$this->loadComponent('phpmailerComponent');
			$this->phpmailerComponent->create($_POST['subject'],$_POST['messages'],$_POST['email']);
			wp_send_json_success();
		}else{
			wp_send_json_error();
		}
	}

	public function registerAdminMenu()
	{
		add_menu_page('Izwebz General','Izwebz General','manage_options','izwebz_core',array($this,'general'),CORE_IMAGE_URL.'izwebz.png','3b');
		add_submenu_page('izwebz_core','FaceBook Users', 'FaceBook Users', 'manage_options', 'facebook_users', array($this,'general'));
		add_submenu_page('izwebz_core','PracticeTest', 'PracticeTest', 'manage_options', 'manage_practice_test', array($this,'general'));
	}

	public function registerAdminSettings()
	{
		add_settings_section('izwebz_core',' ',array($this,'general'),'izwebz_core');
		add_settings_section('facebook_users',' ',array($this,'FaceBookUsers'),'facebook_users');
		add_settings_section('manage_practice_test',' ',array($this,'managePracticeTest'),'manage_practice_test');
	}

	public function general()
	{	
		$this->render('admin_general',array('tab'=>getAdminMenuPage($_GET['page'])));
	}

	public function FaceBookUsers()
	{
		$this->loadModel('FaceBookLoginModel');
		$this->loadComponent(array('adminTableViewComponent','cacheComponent'));
		// Require action model is runActionAdminTableView
		$this->adminTableViewComponent->callAction = $this->FaceBookLoginModel;
		$this->adminTableViewComponent->config = array(
			'plural' => 'FaceBook Users',
	        'singular'=> 'facebook_users',
	        'screen' => null
		);
		$this->adminTableViewComponent->bulk_action = array(
			'delete'=>'Delete',
			'blacklist'=>'Move to BlackList'
		);
		$this->adminTableViewComponent->tableView = $this->FBLogin;
		$this->adminTableViewComponent->columns = array(
			'c1'=>'Avatar',
			'c2'=>'User ID',
			'c3'=>'Email',
			'c4'=>'Name',
			'c5'=>'Gender',
			'c6'=>'Home Town',
			'c7'=>'FaceBook URL',
			'c8'=>'User Register',
			'c9'=>'Last Login'
		);
		$this->adminTableViewComponent->sortable_columns = array(
			'c4'=>array('full_name'),
			'c3'=>array('user_email'),
			'c5'=>array('gender'),
			'c6'=>array('hometown'),
			'c8'=>array('date_register'),
			'c9'=>array('last_login_time')
		);
		$this->adminTableViewComponent->rows = array(
			'r1'=>array('profile_picture','img'),
			'r2'=>array('user_id','string'),
			'r3'=>array('user_email','email'),
			'r4'=>array('full_name','string'),
			'r5'=>array('gender','string'),
			'r6'=>array('hometown','string'),
			'r7'=>array('link','url'),
			'r8'=>array('date_register','date'),
			'r9'=>array('last_login_time','date')
		);
		// $this->adminTableViewComponent->search_col = array('full_name','gender','user_id');
		$this->adminTableViewComponent->search_by = 'user_email';
		$this->adminTableViewComponent->displayTable();
	}

	public function managePracticeTest()
	{

	}

	public function checkFaceBookUser()
	{
		$this->loadModel('FaceBookLoginModel');
		if(isset($_POST['userID']) && !empty($_POST['userID'])){
			if($this->FaceBookLoginModel->setStatus($_POST['userID']) == true){
				wp_send_json_success();
			}else{
				wp_send_json_error();
			}
		}else{
			wp_send_json_error();
		}
	}

	public function updateStatusFaceBookUser()
	{
		$this->loadModel('FaceBookLoginModel');
		if(isset($_POST['userID']) && !empty($_POST['userID'])){
			if($this->FaceBookLoginModel->updateStatus($_POST['userID']) == true){
				wp_send_json_success();
			}else{
				wp_send_json_error();
			}
		}
	}

	public function admin_script()
	{
		wp_enqueue_style('admin_practicetest_css',CORE_CSS_URL.'practicetest/admin.practicetest.css');
		$this->registerScript('admin_practicetest_js',CORE_JS_URL.'practicetest/jquery.admin.practicetest.js',array('jquery'));
		$this->registerScript('admin_practicetest_ajax',CORE_JS_URL.'practicetest/ajax.admin.practicetest.js',array('jquery'));
		wp_localize_script('admin_practicetest_ajax','ajax_script', array(
            'ajax_image' => CORE_IMAGE_URL,
            'ajaxurl' => admin_url('admin-ajax.php')
        ));
	}

	public function autoUpdatePracticeTest()
	{
		$this->loadModel(array('PracticeTestTemporaryResultModel','PracticeTestResultModel','PracticeTestModel'));
		if(!empty($_POST['izQuizID']) && !empty($_POST['izUserID'])){
			$getCurrentDoing = $this->PracticeTestTemporaryResultModel->getCurrentDoing($_POST['izQuizID'],$_POST['izUserID']);
			$getResultFirst = $this->PracticeTestResultModel->getCurrentDoing($_POST['izQuizID'],$_POST['izUserID']);
			$isTrue = $getCurrentDoing->is_true;
			$isFalse = $getCurrentDoing->is_false;
			if(!empty($getCurrentDoing->time_stop) && $getCurrentDoing->time_stop <= getTimeServer() && $getCurrentDoing->is_success==0){
				if(empty($isTrue) && empty($isFalse)){
					$this->PracticeTestTemporaryResultModel->update(array(
						'number_answer'=>$getCurrentDoing->number_answer+1,
						'time_finish'=>$getCurrentDoing->time_stop,
						'next_date_answer'=>date('Y-m-d H:i:s',strtotime(getTimeServer()."+ 12 hours")),
						'is_success'=>1
					),array('practice_test_id'=>$_POST['izQuizID'],'user_id'=>$_POST['izUserID']));
					if(empty($getResultFirst->time_finish)){
						$this->PracticeTestResultModel->update(array(
							'number_answer'=>$getCurrentDoing->number_answer+1,
							'time_finish'=>$getCurrentDoing->time_stop,
						),array('practice_test_id'=>$_POST['izQuizID'],'user_id'=>$_POST['izUserID']));
					}else{
						$this->PracticeTestResultModel->update(array(
							'number_answer'=>$getCurrentDoing->number_answer+1
						),array('practice_test_id'=>$_POST['izQuizID'],'user_id'=>$_POST['izUserID']));
					}
					wp_send_json_success();
				}else{
					$timePost = $this->PracticeTestModel->getTime($_POST['izQuizID']);
					if($getCurrentDoing->number_correct>0){
						$calPoint = calPoint(array(
							'time_start'=>$getCurrentDoing->time_start,
							'time_stop'=>getTimeServer(),
							'time_doing'=>$timePost,
							'point'=>$getCurrentDoing->number_correct
						)); 
					}else{
						$calPoint = 0;
					}
					$this->PracticeTestTemporaryResultModel->update(array(
						'number_answer'=>$getCurrentDoing->number_answer+1,
						'time_finish'=>getTimeServer(),
						'point'=>$calPoint,
						'next_date_answer'=>date('Y-m-d H:i:s',strtotime(getTimeServer()."+ 12 hours")),
						'is_success'=>1
					),array('practice_test_id'=>$_POST['izQuizID'],'user_id'=>$_POST['izUserID']));
					if(empty($getResultFirst->time_finish)){
						$this->PracticeTestResultModel->update(array(
							'is_true'=>$getCurrentDoing->is_true,
							'is_false'=>$getCurrentDoing->is_false,
							'time_finish'=>$getCurrentDoing->time_stop,
							'progressbar'=>$getCurrentDoing->progressbar,
							'number_correct'=>$getCurrentDoing->number_correct,
							'number_wrong'=>$getCurrentDoing->number_wrong,
							'number_answer'=>$getCurrentDoing->number_answer+1,
							'accumulation_point'=>$calPoint
						),array('practice_test_id'=>$_POST['izQuizID'],'user_id'=>$_POST['izUserID']));
					}else{
						$this->PracticeTestResultModel->update(array(
							'number_answer'=>$getCurrentDoing->number_answer+1,
							'accumulation_point'=>($getResultFirst->accumulation_point+$calPoint)
						),array('practice_test_id'=>$_POST['izQuizID'],'user_id'=>$_POST['izUserID']));
					}
					$this->PracticeTestResultModel->calPointOfUser($_POST['izUserID']);
					wp_send_json_success();
				}
			}else{
				wp_send_json_error();
			}
		}else{
			wp_send_json_error();
		}
	}

	public function startPracticeTest()
	{
		$this->loadModel(array('PracticeTestTemporaryResultModel','PracticeTestResultModel'));
		if(!empty($_POST['izQuizID']) && !empty($_POST['izUserID'])){
			$resultExist = $this->PracticeTestResultModel->exists($_POST['izQuizID'],$_POST['izUserID']);
			$resultTMPExist = $this->PracticeTestTemporaryResultModel->isExists($_POST['izQuizID'],$_POST['izUserID']);
			$isSuccess = $this->PracticeTestTemporaryResultModel->isSuccess($_POST['izQuizID'],$_POST['izUserID']);
			if($resultExist==false && $resultTMPExist==false){
				$this->PracticeTestResultModel->insert(array(
					'practice_test_id'=>$_POST['izQuizID'],
					'user_id'=>$_POST['izUserID'],
					'time_start'=>getTimeServer(),
					'time_stop'=>date('Y-m-d H:i:s',strtotime(getTimeServer()." +".$_POST['timer']." minutes"))
				));
				$this->PracticeTestTemporaryResultModel->insert(array(
					'practice_test_id'=>$_POST['izQuizID'],
					'user_id'=>$_POST['izUserID'],
					'time_start'=>getTimeServer(),
					'time_stop'=>date('Y-m-d H:i:s',strtotime(getTimeServer()." +".$_POST['timer']." minutes"))
				));
				wp_send_json_success();
			}else if($resultExist == true && $isSuccess==true){
				$this->PracticeTestTemporaryResultModel->update(array(
					'time_start'=>getTimeServer(),
					'time_stop'=>date('Y-m-d H:i:s',strtotime(getTimeServer()." +".$_POST['timer']." minutes")),
					'is_success'=>0,
					'is_true'=>'',
					'is_false'=>'',
					'number_correct'=>'',
					'number_wrong'=>'',
					'current_question'=>0,
					'progressbar'=>'',
					'point'=>0
				),array('practice_test_id'=>$_POST['izQuizID'],'user_id'=>$_POST['izUserID']));
				wp_send_json_success();
			}else{
				wp_send_json_error();
			}
		}else{
			wp_send_json_error();
		}
	}

	public function updatePracticeTestTemporaryResult()
	{
		$this->loadModel(array('PracticeTestAnswerModel','PracticeTestTemporaryResultModel','PracticeTestResultModel','PracticeTestModel'));
		if(!empty($_POST['izQuizID']) && !empty($_POST['izUserID'])){
			if(!empty($_POST['izQuestionID']) && !empty($_POST['izAnswer'])){
				$numberCorrect = $this->PracticeTestTemporaryResultModel->getNumberAnswerCorrect($_POST['izQuizID'],$_POST['izUserID']);
				$numberWrong = $this->PracticeTestTemporaryResultModel->getNumberAnswerWrong($_POST['izQuizID'],$_POST['izUserID']);
				$numAnswer = $this->PracticeTestTemporaryResultModel->getNumAnswer($_POST['izQuizID'],$_POST['izUserID']);
				$nextDoing = $this->PracticeTestTemporaryResultModel->getNextDoing($_POST['izQuizID'],$_POST['izUserID']);
				$currentPoint = $this->PracticeTestResultModel->getPoints($_POST['izQuizID'],$_POST['izUserID']);
				$timePost = $this->PracticeTestModel->getTime($_POST['izQuizID']);
				$dateTimeDoing = $this->PracticeTestTemporaryResultModel->getTimerStop($_POST['izQuizID'],$_POST['izUserID']);
				if($this->PracticeTestTemporaryResultModel->isExists($_POST['izQuizID'],$_POST['izUserID'])==false){
					if(!empty($_POST['valAnswer']) && $_POST['valAnswer']=="yes" || $_POST['valAnswer']=="no"){
						$is_answer = $this->PracticeTestAnswerModel->checkAnserCorrectYesNo($_POST['izAnswer'],$_POST['valAnswer']);
						$resultOfUser = $this->PracticeTestTemporaryResultModel->getResultOfUser($_POST['izQuizID'],$_POST['izUserID']);
						
						$is_true = $resultOfUser->is_true;
						$is_false = $resultOfUser->is_false;
						
						$listTrue = strpos($resultOfUser->is_true,",") !==false ? explode(",",$resultOfUser->is_true) : $resultOfUser->is_true;
						$listFalse = strpos($resultOfUser->is_false,",") !==false ? explode(",",$resultOfUser->is_false) : $resultOfUser->is_false;
						
						if($is_answer==true){
							if(count($listTrue)>1){
								if(!in_array($_POST['izAnswer'], $listTrue)){
									$is_true = !empty($resultOfUser->is_true) ? $resultOfUser->is_true.",".$_POST['izAnswer'] : $_POST['izAnswer'];
								}
							}else{
								if(!empty($listTrue) && strpos($_POST['izAnswer'],$listTrue)===false){
									$is_true = !empty($listTrue) ? $listTrue.",".$_POST['izAnswer'] : $_POST['izAnswer'];
								}else{
									$is_true = $_POST['izAnswer'];
								}
							}
							$numberCorrect=$numberCorrect+1;
						}else{
							if(count($listFalse)>1){
								if(!in_array($_POST['izAnswer'], $listFalse)){
									$is_false = !empty($resultOfUser->is_false) ? $resultOfUser->is_false.",".$_POST['izAnswer'] : $_POST['izAnswer'];
								}
							}else{
								if(!empty($listFalse) && strpos($_POST['izAnswer'],$listFalse)===false){
									$is_false = !empty($listFalse) ? $listFalse.",".$_POST['izAnswer'] : $_POST['izAnswer'];
								}else{
									$is_false = $_POST['izAnswer'];
								}
								
							}
							$numberWrong=$numberWrong+1;
						}
					}else{
						$is_answer = $this->PracticeTestAnswerModel->checkAnswerCorrect($_POST['izAnswer']);
						$resultOfUser = $this->PracticeTestTemporaryResultModel->getResultOfUser($_POST['izQuizID'],$_POST['izUserID']);
						$is_true = $resultOfUser->is_true;
						$is_false = $resultOfUser->is_false;
						$listTrue = strpos($resultOfUser->is_true,",") !==false ? explode(",",$resultOfUser->is_true) : $resultOfUser->is_true;
						$listFalse = strpos($resultOfUser->is_false,",") !==false ? explode(",",$resultOfUser->is_false) : $resultOfUser->is_false;
						
						if($is_answer==true){
							if(count($listTrue)>1){
								if(!in_array($_POST['izAnswer'], $listTrue)){
									$is_true = !empty($resultOfUser->is_true) ? $resultOfUser->is_true.",".$_POST['izAnswer'] : $_POST['izAnswer'];
								}
							}else{
								if(!empty($listTrue) && strpos($_POST['izAnswer'],$listTrue)===false){
									$is_true = !empty($listTrue) ? $listTrue.",".$_POST['izAnswer'] : $_POST['izAnswer'];
								}else{
									$is_true = $_POST['izAnswer'];
								}
							}
							$numberCorrect=$numberCorrect+1;
						}else{
							if(count($listFalse)>1){
								if(!in_array($_POST['izAnswer'], $listFalse)){
									$is_false = !empty($resultOfUser->is_false) ? $resultOfUser->is_false.",".$_POST['izAnswer'] : $_POST['izAnswer'];
								}
							}else{
								if(!empty($listFalse) && strpos($_POST['izAnswer'],$listFalse)===false){
									$is_false = !empty($listFalse) ? $listFalse.",".$_POST['izAnswer'] : $_POST['izAnswer'];
								}else{
									$is_false = $_POST['izAnswer'];
								}
								
							}
							$numberWrong=$numberWrong+1;
						}
					} // End check isYesNoQuestion

					$this->PracticeTestTemporaryResultModel->update(array(
						'is_true'=>$is_true,
						'is_false'=>$is_false,
						'number_correct'=>$numberCorrect,
						'number_wrong'=>$numberWrong,
						'current_question'=>$_POST['currentQuestion'],
						'progressbar'=>$_POST['percentDoing'],
						'is_success'=>0
					),array('practice_test_id'=>$_POST['izQuizID'],'user_id'=>$_POST['izUserID']));

					wp_send_json_success();
				}else{
					if($this->PracticeTestTemporaryResultModel->isSuccess($_POST['izQuizID'],$_POST['izUserID'])==false){
						if(!empty($_POST['valAnswer']) && $_POST['valAnswer']=="yes" || $_POST['valAnswer']=="no"){
							$is_answer = $this->PracticeTestAnswerModel->checkAnserCorrectYesNo($_POST['izAnswer'],$_POST['valAnswer']);
							$resultOfUser = $this->PracticeTestTemporaryResultModel->getResultOfUser($_POST['izQuizID'],$_POST['izUserID']);
							$is_true = $resultOfUser->is_true;
							$is_false = $resultOfUser->is_false;
							$listTrue = strpos($resultOfUser->is_true,",") !==false ? explode(",",$resultOfUser->is_true) : $resultOfUser->is_true;
							$listFalse = strpos($resultOfUser->is_false,",") !==false ? explode(",",$resultOfUser->is_false) : $resultOfUser->is_false;
							if($is_answer==true){
								if(count($listTrue)>1){
									if(!in_array($_POST['izAnswer'], $listTrue)){
										$is_true = !empty($resultOfUser->is_true) ? $resultOfUser->is_true.",".$_POST['izAnswer'] : $_POST['izAnswer'];
									}
								}else{
									if(!empty($listTrue) && strpos($_POST['izAnswer'],$listTrue)===false){
										$is_true = !empty($listTrue) ? $listTrue.",".$_POST['izAnswer'] : $_POST['izAnswer'];
									}else{
										$is_true = $_POST['izAnswer'];
									}
								}
								$numberCorrect=$numberCorrect+1;
							}else{
								if(count($listFalse)>1){
									if(!in_array($_POST['izAnswer'], $listFalse)){
										$is_false = !empty($resultOfUser->is_false) ? $resultOfUser->is_false.",".$_POST['izAnswer'] : $_POST['izAnswer'];
									}
								}else{
									if(!empty($listFalse) && strpos($_POST['izAnswer'],$listFalse)===false){
										$is_false = !empty($listFalse) ? $listFalse.",".$_POST['izAnswer'] : $_POST['izAnswer'];
									}else{
										$is_false = $_POST['izAnswer'];
									}
									
								}
								$numberWrong=$numberWrong+1;
							}
						}else{
							$is_answer = $this->PracticeTestAnswerModel->checkAnswerCorrect($_POST['izAnswer']);
							$resultOfUser = $this->PracticeTestTemporaryResultModel->getResultOfUser($_POST['izQuizID'],$_POST['izUserID']);
							$is_true = $resultOfUser->is_true;
							$is_false = $resultOfUser->is_false;
							$listTrue = strpos($resultOfUser->is_true,",") !==false ? explode(",",$resultOfUser->is_true) : $resultOfUser->is_true;
							$listFalse = strpos($resultOfUser->is_false,",") !==false ? explode(",",$resultOfUser->is_false) : $resultOfUser->is_false;
							
							if($is_answer==true){
								if(count($listTrue)>1){
									if(!in_array($_POST['izAnswer'], $listTrue)){
										$is_true = !empty($resultOfUser->is_true) ? $resultOfUser->is_true.",".$_POST['izAnswer'] : $_POST['izAnswer'];
									}
								}else{
									if(!empty($listTrue) && strpos($_POST['izAnswer'],$listTrue)===false){
										$is_true = !empty($listTrue) ? $listTrue.",".$_POST['izAnswer'] : $_POST['izAnswer'];
									}else{
										$is_true = $_POST['izAnswer'];
									}
								}
								$numberCorrect=$numberCorrect+1;
							}else{
								if(count($listFalse)>1){
									if(!in_array($_POST['izAnswer'], $listFalse)){
										$is_false = !empty($resultOfUser->is_false) ? $resultOfUser->is_false.",".$_POST['izAnswer'] : $_POST['izAnswer'];
									}
								}else{
									if(!empty($listFalse) && strpos($_POST['izAnswer'],$listFalse)===false){
										$is_false = !empty($listFalse) ? $listFalse.",".$_POST['izAnswer'] : $_POST['izAnswer'];
									}else{
										$is_false = $_POST['izAnswer'];
									}
									
								}
								$numberWrong=$numberWrong+1;
							}
						} // End check isYesNoQuestion

						$getTimeResult = $this->PracticeTestTemporaryResultModel->getTimeResult($_POST['izQuizID'],$_POST['izUserID']);
						if($numberCorrect>0){
							$calPoint = calPoint(array(
								'time_start'=>$getTimeResult->time_start,
								'time_stop'=>getTimeServer(),
								'time_doing'=>$timePost,
								'point'=>$numberCorrect
							)); 
						}else{
							$calPoint = 0;
						}

						if($numAnswer < 1){
							$this->PracticeTestTemporaryResultModel->update(array(
								'is_true'=>$is_true,
								'is_false'=>$is_false,
								'number_correct'=>$numberCorrect,
								'number_wrong'=>$numberWrong,
								'current_question'=>$_POST['currentQuestion'],
								'progressbar'=>$_POST['percentDoing'],
								'time_finish'=>($_POST['total']==$_POST['currentQuestion']) ? getTimeServer() : '',
								'next_date_answer'=>($_POST['total']==$_POST['currentQuestion']) ? date('Y-m-d H:i:s',strtotime($dateTimeDoing."+ 12 hours")) : null,
								'point'=>($_POST['total']==$_POST['currentQuestion']) ? $calPoint : 0,
								'is_success'=>($_POST['total']==$_POST['currentQuestion']) ? 1 : 0,
								'number_answer'=>($_POST['total']==$_POST['currentQuestion']) ? 1 : 0,
							),array('user_id'=>$_POST['izUserID'],'practice_test_id'=>$_POST['izQuizID']));

							if($this->PracticeTestTemporaryResultModel->isSuccess($_POST['izQuizID'],$_POST['izUserID'])==true){

								$this->PracticeTestResultModel->update(array(
									'is_true'=>$is_true,
									'is_false'=>$is_false,
									'time_finish'=>getTimeServer(),
									'progressbar'=>$_POST['percentDoing'],
									'number_correct'=>$numberCorrect,
									'number_wrong'=>$numberWrong,
									'number_answer'=>1,
									'accumulation_point'=>($currentPoint+$calPoint)
								),array('practice_test_id'=>$_POST['izQuizID'],'user_id'=>$_POST['izUserID']));
								$this->PracticeTestResultModel->calPointOfUser($_POST['izUserID']);

							}
							wp_send_json_success();

						}else{
							$this->PracticeTestTemporaryResultModel->update(array(
								'is_true'=>$is_true,
								'is_false'=>$is_false,
								'number_correct'=>$numberCorrect,
								'number_wrong'=>$numberWrong,
								'current_question'=>$_POST['currentQuestion'],
								'progressbar'=>$_POST['percentDoing'],
								'point'=>($_POST['total']==$_POST['currentQuestion']) ? $calPoint : $currentPoint,
								'next_date_answer'=>($_POST['total']==$_POST['currentQuestion']) ? date('Y-m-d H:i:s',strtotime($dateTimeDoing."+ 12 hours")) : $dateTimeDoing,
								'time_finish'=>($_POST['total']==$_POST['currentQuestion']) ? getTimeServer() : '',
								'is_success'=>($_POST['total']==$_POST['currentQuestion']) ? 1 : 0,
								'number_answer'=>($_POST['total']==$_POST['currentQuestion']) ? $numAnswer+1 : $numAnswer,
							),array('user_id'=>$_POST['izUserID'],'practice_test_id'=>$_POST['izQuizID']));


							if($this->PracticeTestTemporaryResultModel->isSuccess($_POST['izQuizID'],$_POST['izUserID'])==true){
								$this->PracticeTestResultModel->update(array(
									'number_answer'=>(int)$numAnswer+1,
									'accumulation_point'=>($currentPoint+$calPoint) 
								),array('user_id'=>$_POST['izUserID'],'practice_test_id'=>$_POST['izQuizID']));
								$this->PracticeTestResultModel->calPointOfUser($_POST['izUserID']);
							}
							wp_send_json_success();
						}
					}
				}
			}else{
				wp_send_json_error();
			}
		}else{
			wp_send_json_error();
		}
	}

	public function activePracticeTest()
	{
		
	}

	public function createPracticeTest()
	{
		$this->loadModel(array('PracticeTestModel','PracticeTestQuestionModel','PracticeTestAnswerModel'));
		$post_id = $_GET['post'];
		$author_id = get_current_user_id();
		$getPracticeTest = $this->PracticeTestModel->getPracticeTest($post_id);
		$getPostByAuthor = $this->PracticeTestModel->getPostByID($author_id,$post_id);
		$getPracticeTestQuestion = $this->PracticeTestQuestionModel->getPracticeTestQuestion($getPracticeTest->id);
		$this->render('metabox',array(
			'post_id'=>$post_id,
			'author_id'=>$author_id,
			'practice_test'=>$getPracticeTest,
			'fieldquestion'=>$getPracticeTestQuestion,
			'create_allow'=>(is_super_admin() || $author_id == $getPracticeTest->author_id || !empty($getPostByAuthor)) ? true : false,
		));
	}

	public function removePracticeTestQuestion()
	{
		if(isset($_POST['question_id']) && !empty($_POST['question_id'])){
			$this->loadModel(array('PracticeTestQuestionModel','PracticeTestAnswerModel'));
			$this->PracticeTestQuestionModel->delete(array('id'=>$_POST['question_id']));
			$this->PracticeTestAnswerModel->delete(array('question_id'=>$_POST['question_id']));
			wp_send_json_success();
		}else{
			wp_send_json_error();
		}
	}

	public function applyPracticeTestAnswer()
	{
		if(!empty($_POST['answer']) && !empty($_POST['question_id'])){
			$this->loadModel('PracticeTestAnswerModel');
			$totalAnswerByQuestion = $this->PracticeTestAnswerModel->getPracticeTestAnswer($_POST['question_id']);
			if($_POST['answer'] == "True/False"){
				if(empty($_POST['answer_id'])){
					$answer_id = $this->PracticeTestAnswerModel->insert(array(
						'question_id'=>$_POST['question_id'],
						'answer'=>$_POST['answer'],
						'is_answer'=>($_POST['is_answer']=="True") ? 1 : 0
					));
					wp_send_json_success($answer_id);
				}else{
					$this->PracticeTestAnswerModel->update(array(
						'is_answer'=>($_POST['is_answer']=="True") ? 1 : 0
					),array('id'=>$_POST['answer_id'],'question_id'=>$_POST['question_id']));
					wp_send_json_success((int)$_POST['answer_id']);
				}
			}else{
				if(isset($_POST['is_answer']) && !empty($_POST['is_answer'])){
					$this->PracticeTestAnswerModel->update(array(
						'is_answer'=>0
					),array('question_id'=>$_POST['question_id']));
					$this->PracticeTestAnswerModel->update(array(
						'is_answer'=>1
					),array('id'=>$_POST['answer_id'],'question_id'=>$_POST['question_id']));
					wp_send_json_success((int)$_POST['answer_id']);
				}else{
					if(empty($_POST['answer_id']) && count($totalAnswerByQuestion) < 4){
						$answer_id = $this->PracticeTestAnswerModel->insert(array(
							'question_id'=>$_POST['question_id'],
							'answer'=>$_POST['answer']
						));
						wp_send_json_success($answer_id);
					}else{
						$this->PracticeTestAnswerModel->update(array(
							'answer'=>$_POST['answer']
						),array('id'=>$_POST['answer_id'],'question_id'=>$_POST['question_id']));
						wp_send_json_success((int)$_POST['answer_id']);
					}
				}
			}
		}else{
			wp_send_json_error();
		}
	}

	public function savePracticeTestQuestion()
	{
		if(!empty($_POST['question']) && !empty($_POST['practicetest_id'])){
			$this->loadModel('PracticeTestQuestionModel');
				if(empty($_POST['question_id'])){
					$question_id = $this->PracticeTestQuestionModel->insert(array(
						'practice_test_id'=>$_POST['practicetest_id'],
						'question'=>$_POST['question']
					));
					wp_send_json_success($question_id);
				}else{
					$this->PracticeTestQuestionModel->update(array(
						'question'=>$_POST['question']
					),array('id'=>$_POST['question_id'],'practice_test_id'=>$_POST['practicetest_id']));
					wp_send_json_success((int)$_POST['question_id']);
				}
		}else{
			wp_send_json_error();
		}
	}

	public function savePracticeTestInformation()
	{
		if(!empty($_POST['post_id']) && !empty($_POST['author_id'])){
			$this->loadModel('PracticeTestModel');
			if($this->PracticeTestModel->hasPracticeTest($_POST['post_id'])==false){
				$practicetest_id = $this->PracticeTestModel->insert(array(
					'author_id'=>$_POST['author_id'],
					'post_id'=>$_POST['post_id'],
					'level'=>$_POST['level'],
					'time'=>$_POST['time'],
					'created'=>date('Y-m-d H:i:s'),
					'requirements'=>$_POST['requirements'],
					'note'=>$_POST['note']
				));
			}else{
				$practicetest_id = $this->PracticeTestModel->update(array(
					'author_id'=>$_POST['author_id'],
					'post_id'=>$_POST['post_id'],
					'level'=>$_POST['level'],
					'time'=>$_POST['time'],
					'created'=>date('Y-m-d H:i:s'),
					'requirements'=>$_POST['requirements'],
					'note'=>$_POST['note']
				),array('post_id'=>$_POST['post_id']));
			}
			wp_send_json_success($practicetest_id);
		}else{
			wp_send_json_error();
		}
	}

	public function saveUserProfile()
	{
		if(!empty($_POST['data']['id'])){
			$this->loadModel('FaceBookLoginModel');
			$data = $_POST['data'];
			$loginCount = $this->FaceBookLoginModel->getLoginCount($data['id']);
			if($this->FaceBookLoginModel->userExists($data['id']) == false) {
				$this->FaceBookLoginModel->insert(array(
					'user_id'=>$data['id'],
					'user_email'=>$data['email'],
					'education'=>!empty($data['education'][0]) ? implode(";",$data['education']) : "",
					'first_name'=>$data['first_name'],
					'last_name'=>$data['last_name'],
					'full_name'=>$data['name'],
					'gender'=>ucfirst($data['gender']),
					'hometown'=>!empty($data['hometown']) ? ltrim(implode(";",$data['hometown']),';') : "",
					'link'=>$data['link'],
					'locale'=>$data['locale'],
					'location'=>!empty($data['location']) ? ltrim(implode(";",$data['location']),';') : "",
					'timezone'=>$data['timezone'],
					'updated_time'=>$data['updated_time'],
					'username'=>$data['username'],
					'profile_picture'=>$data['profile_picture'],
					'work'=>!empty($data['work'][0]) ? implode(";",$data['work']) : "",
					'last_login_time'=>date('Y-m-d H:i:s'),
					'login_count'=>1,
					'date_register'=>date('Y-m-d H:i:s'),
					'verified'=>$data['verified'],
					'isLogin'=>1
				));
			}else{
				$this->FaceBookLoginModel->update(array(
					'user_email'=>$data['email'],
					'education'=>!empty($data['education'][0]) ? implode(";",$data['education']) : "",
					'first_name'=>$data['first_name'],
					'last_name'=>$data['last_name'],
					'full_name'=>$data['name'],
					'gender'=>ucfirst($data['gender']),
					'hometown'=>!empty($data['hometown']) ? ltrim(implode(";",$data['hometown']),';') : "",
					'link'=>$data['link'],
					'locale'=>$data['locale'],
					'location'=>!empty($data['location']) ? ltrim(implode(";",$data['location']),';') : "",
					'timezone'=>$data['timezone'],
					'updated_time'=>$data['updated_time'],
					'username'=>$data['username'],
					'profile_picture'=>$data['profile_picture'],
					'work'=>!empty($data['work'][0]) ? implode(";",$data['work']) : "",
					'last_login_time'=>date('Y-m-d H:i:s'),
					'login_count'=> $loginCount + 1,
					'verified'=>$data['verified'],
					'isLogin'=>1
				),array('user_id'=>$data['id']));
			}
			wp_send_json_success();
		}else{
			wp_send_json_error();
		}
	}

	public function fixWPRedirect()
    {
        ob_start();
    }

    public function registerSessions() 
    {
        if (!session_id()) {
            session_start();
        }
    }

}